﻿using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using WindowsGame.Enums;
using WindowsGame.Library;

namespace WindowsGame.Components
{
	public class ModelComponent : BaseGameComponent
	{
		private Model model;
		private Texture2D texture;
		private Matrix[] transforms;

		public override void LoadContent()
		{
			// Some models have same texture name.
			if (String.IsNullOrEmpty(TextureName))
			{
				TextureName = ModelName;
			}

			model = Engine.Content.Load<Model>(ModelName);
			texture = Engine.Content.Load<Texture2D>(TextureName);

			transforms = new Matrix[model.Bones.Count];
			model.CopyAbsoluteBoneTransformsTo(transforms);
		}

		public void Draw(Matrix worldMatrix)
		{
			Matrix viewMatrix = Engine.Camera.ViewMatrix;
			Matrix projectionMatrix = Engine.Camera.ProjectionMatrix;

			foreach (ModelMesh mesh in model.Meshes)
			{
				foreach (BasicEffect effect in mesh.Effects)
				{
					effect.World = transforms[mesh.ParentBone.Index] * worldMatrix;
					effect.View = viewMatrix;
					effect.Projection = projectionMatrix;
					effect.Texture = texture;
					effect.EnableDefaultLighting();
				}

				mesh.Draw();
			}
		}

		public ShipClass ShipClass	{ get; set; }
		public String ModelName		{ get; set; }
		public String TextureName	{ get; set; }
	}
}